package com.waya.web.browser.webview;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

import com.waya.web.browser.common.util.ApkUtil;
import com.waya.web.browser.event.EventHandlerImp;

import java.lang.ref.WeakReference;

/**
 * Created by JesseHev on 2018/1/16.
 * describe: 申明JS调用的Native的接口
 * androidContext
 */

public class AndroidBrowser {

    private static final String TAG = "AndroidBrowser";

    private Context mContext;

    private WebView webView;


    private Handler mHandler;

    public AndroidBrowser(Context mContext, WebView webView) {
        this.mContext = mContext;
        this.webView = webView;
        mHandler = new Handler(Looper.getMainLooper());
    }

    public AndroidBrowser(Context context) {
        mContext = context;
    }

    @JavascriptInterface
    public void install(String url) {
        ApkUtil.downLoadAndInstallApk(mContext, url);
    }

    @JavascriptInterface
    public void unInstall(String packageName) {
        ApkUtil.uninstall(mContext, packageName);
    }

    @JavascriptInterface
    public boolean isInstall(String packageName) {
        return ApkUtil.isInstall(mContext, packageName);
    }

    @JavascriptInterface
    public int getAppVersion(String packageName) {
        return ApkUtil.getAppVersion(mContext, packageName);
    }


    @JavascriptInterface
    public void goBack() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, "返回上个页面...", Toast.LENGTH_SHORT).show();
                EventHandlerImp handlerImp = EventHandlerImp.getInstance(webView,webView.getUrl());
                if (!handlerImp.back()) {
                    finish();
                }
            }
        });
    }

    @JavascriptInterface
    public void finish() {
        if (mContext != null && mContext instanceof Activity) {
            ((Activity) mContext).finish();
        }
    }
}
